package redis

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"me/123/common/dao/mysql"
	"me/123/common/global"
	"me/123/common/model"

	"time"
)

func PreheatStockToRedisLPush(spikeProductsId int64, stock int64) error {
	key := fmt.Sprintf("SpikeProducts:%d", spikeProductsId)
	lockKey := fmt.Sprintf("Lock:SpikeProducts:%d", spikeProductsId)
	lockValue := "locked"
	result, err := global.Rdb.SetNX(context.Background(), lockKey, lockValue, time.Second*30).Result()
	if err != nil {
		return fmt.Errorf("获取锁失败 err:%v", err)
	}
	if !result {
		return fmt.Errorf("无法获取锁")
	}
	defer func() {
		if err := global.Rdb.Del(context.Background(), lockKey).Err(); err != nil {
			fmt.Printf("释放锁失败%s\n", lockKey)
		}
	}()

	err = global.Rdb.Del(context.Background(), key).Err()
	if err != nil {
		return fmt.Errorf("未能删除以前的Stock列表: %w", err)
	}

	// 将商品库存逐个添加到 Redis List 中
	for i := 0; i < int(stock); i++ {
		err := global.Rdb.LPush(context.Background(), key, spikeProductsId).Err()
		if err != nil {
			return fmt.Errorf("添加队列失败: %w", err)
		}
	}
	fmt.Printf("Successfully preheated %d stock items for products %d to Redis List\n", stock, spikeProductsId)
	return nil
}

func SpikeProductsDel(id uint64) error {
	key := fmt.Sprintf("SpikeProducts:%d", id)
	return global.Rdb.Del(context.Background(), key).Err()
}

func Len(productID uint) int64 {
	key := fmt.Sprintf("SpikeProducts:%d", productID)
	return global.Rdb.LLen(context.Background(), key).Val()
}

func SpikeProductsRop(id int64) error {
	key := fmt.Sprintf("SpikeProducts:%d", id)
	return global.Rdb.LPop(context.Background(), key).Err()
}

func GetList(query *gorm.DB) (result []model.EbStoreProduct, err error) {
	s, err := global.Rdb.Get(context.Background(), "list").Result()
	if err == nil {
		var p []model.EbStoreProduct
		err := json.Unmarshal([]byte(s), &p)
		if err != nil {
			zap.S().Error("反解析失败", zap.Error(err))
			return nil, err
		}
		return p, nil
	}

	list, err := mysql.QueryList(query)
	if err != nil {
		return nil, err
	}
	fmt.Println(list)
	marshal, err := json.Marshal(list)
	if err != nil {
		zap.S().Error("解析失败", zap.Error(err))
		return nil, err
	}
	err = global.Rdb.Set(context.Background(), "list", marshal, time.Second*60).Err()
	if err != nil {
		return nil, err
	}
	return nil, errors.New("已存入redis")
}
